<!-- 业务对冲 -->
<template>
  <div class="collpay-list">
    <div ref="dgtools" class="filter-container">
      <div class="dgts-fm dc-list">
        <el-date-picker
          v-model="dgPs.startTime"
          placeholder="开始日期"
          style="width: 125px"
          value-format="yyyy-MM-dd"
        />
        <el-date-picker
          v-model="dgPs.endTime"
          placeholder="结束日期"
          style="width: 125px"
          value-format="yyyy-MM-dd"
        />

        <el-select
          v-model="dgPs.companyId"
          clearable filterable
          placeholder="单位（用车/供车单位）"
          remote reserve-keyword
          :remote-method="queryCusPageList ">
          <el-option
            v-for="it in clientList"
            :key="it.id"
            :label="it.unitName"
            :value="it.id"
            @click.native="selectCus(it)">
            <span>{{it.unitName}}</span>
            <span>{{it.baseUserId.realName}}</span>
          </el-option>
        </el-select>

        <el-select
          v-model="dgPs.companyLinkman"
          clearable filterable
          :placeholder="'联系人'"
          style="width: 140px">
          <el-option
            v-for="it in dutyManList"
            :key="it.uname"
            :label="it.realName"
            :value="it.uname">
          </el-option>
        </el-select>

        <el-select
          v-model="dgPs.serviceMan"
          clearable filterable
          style="width: 120px"
          placeholder="请选择业务员">
          <el-option
            v-for="it in serviceManList"
            :key="it.baseUserId.uname"
            :label="it.baseUserId.realName"
            :value="it.baseUserId.uname">
          </el-option>
        </el-select>

        <el-input
          v-model="dgPs.routeDetail"
          style="width: 140px"
          placeholder="行程详情">
        </el-input>

        <el-input
          v-model="dgPs.operMark"
          style="width: 140px"
          placeholder="操作编号">
        </el-input>

        <div>
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="getDgList(0)">
            搜索
          </el-button>

          <el-button 
            type="primary" 
            icon="el-icon-bottom" 
            @click="onExportExcel(0)">
            导出Excel
          </el-button>
        </div>
      </div>
    </div>

    <div class="collpay-head">
      <div class="collpay-title" style="background: #e1f3d8;">
        <div class="t-title">业务收款-订单列表</div>
        <el-divider direction="vertical"></el-divider>
        <div class="c-blue">订单数量：{{ dgColl.total }}单</div>
      </div>

      <div class="collpay-type">
        <div>结算状态:</div>
        <el-radio-group v-model="dgPs.payStatus">
          <el-radio label="">全部</el-radio>
          <el-radio label="FULL_PAID">已结清</el-radio>
          <el-radio label="UNPAID,DEPOSIT_PAID">未结清</el-radio>
        </el-radio-group>
      </div>
    </div>

    <!-- 收款列表 -->
    <el-table
      :ref="dgColl.tbName"
      :data="dgColl.list"
      row-key="id"
      :height="(bodyHeight - 160) / 2"
      border fit
      :row-class-name="rowClassName"
      @selection-change="selRowColl"
      @select-all="selRowCollAll">
      <el-table-column 
        fixed="left" 
        type="index" 
        label="编号"
        align="center" 
        :resizable="false" 
        width="40">
      </el-table-column>
      <el-table-column 
        fixed="left" 
        type="selection" 
        align="center" 
        :resizable="false" 
        width="40">
      </el-table-column>

      <el-table-column
        v-for="(col, index) in dgColl.columns" 
        :key="index"
        :class-name="dgColl.dgName"
        :prop="col.field"
        :label="col.label"
        :width="col.width">
        <template slot-scope="{ row }">
          <template v-if="col.field == 'routeDetail'">
            <div v-for="(o, i) in row.routeDetail" :key="i">{{(row.routeDetail.length > 1 ? (i+1)+'、' : '')+o}}</div>
          </template>

          <template v-else-if="col.field == 'plateNum'">
            <div v-for="(it, i) in row.driverInfo" :key="i">
              {{it.plateNum}}
            </div>
          </template>

          <template v-else-if="col.field == 'serviceMan'">
            <span>{{row.carOrderBase.serviceMan.split('-')[1]}}{{row.carOrderBase.serviceMan.split('-')[2]}}</span>
          </template>

          <template v-else-if="col.field == 'customId'">
            <div>{{row.carOrderBase.customId.unitName}}</div>
          </template>

          <template v-else-if="col.field == 'operNote'">
            <span v-html="row.operNote.replace(/\(/g, '<br />').replace(/\)/g, '；<br />').replace(/&nbsp;,/g, '<br />')"></span>
          </template>

          <template v-else>{{ getColVal(row, col.field) }}</template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination 
      :total="dgColl.total" 
      :page.sync="dgColl.ps.page" 
      :limit.sync="dgColl.ps.rows" 
      @pagination="getDgList(1)"
    />

    <div class="collpay-totle">
      <div class="t-title">合计</div>
      <el-divider direction="vertical"></el-divider>
      <div class="c-blue">
        已选订单：<span>{{ dgColl.selRows.length + dgPay.selRows.length }}条</span>
      </div>
      <el-divider direction="vertical"></el-divider>
      <div class="c-green">
        应收金额：<span>{{ dgColl.seledTotalCollMoney }}元</span>
      </div>
      <el-divider direction="vertical"></el-divider>
      <div class="c-red">
        应付金额：<span>{{ dgPay.seledTotalPayMoney }}元</span>
      </div>
      <el-divider direction="vertical"></el-divider>
      <div>
        可对冲金额：<span>{{ seledTotalHedgedMoney }}元</span>
      </div>
      <el-divider direction="vertical"></el-divider>
      <div class="c-yellow">
        对冲结差：<span>{{ seledTotalHedgedDiffMoney }}元</span>
      </div>
      <div>
        <el-input
          v-model="operNote"
          style="width: 250px;margin-right: 10px;"
          placeholder="财务备注">
        </el-input>

        <el-button 
          type="primary" 
          icon="el-icon-check"
          @click="confirmHedge">
          确认对冲
        </el-button>

        <el-button 
          type="primary" 
          icon="el-icon-tickets"
          @click="setCollPayHedgedRecordMd({state: true})">
          对冲记录
        </el-button>
      </div>
      
    </div>

    <div class="collpay-head">
      <div class="collpay-title" style="background: #fde2e2;">
        <div class="t-title">业务付款-订单列表</div>
        <el-divider direction="vertical"></el-divider>
        <div class="c-blue">订单总数量：{{ dgPay.total }}单</div>
      </div>
    </div>
    <el-table
      :ref="dgPay.tbName"
      :data="dgPay.list"
      row-key="id"
      :height="(bodyHeight - 160)/2"
      border fit
      :row-class-name="rowClassName"
      @header-dragend="dragHeader"
      @selection-change="selRowPay"
      @select-all="selRowPayAll">
      <el-table-column 
        fixed="left" 
        type="index" 
        label="编号"
        align="center" 
        :resizable="false" 
        width="40">
      </el-table-column>
      <el-table-column 
        fixed="left" 
        type="selection" 
        align="center" 
        :resizable="false" 
        width="40">
      </el-table-column>

      <el-table-column
        v-for="(col, index) in dgPay.columns" 
        :key="index"
        :class-name="dgPay.dgName"
        :prop="col.field"
        :label="col.label"
        :width="col.width">
        <template slot-scope="{row}">
          <template v-if="col.field == 'routeDetail'">
            <span v-if="row.routeDetail" v-html="row.routeDetail.replace(/@/g, '<br />')"></span>
          </template>

          <template v-else-if="col.field == 'plateNum'">
            <span>{{row.disCarId && row.disCarId.plateNum}}</span>
          </template>

          <template v-else-if="col.field == 'serviceMan'">
            <span>{{row.carOrderBase.serviceMan.split('-')[1]}}{{row.carOrderBase.serviceMan.split('-')[2]}}</span>
          </template>

          <template v-else-if="col.field == 'suppCompanyCus'">
            <div>{{row.disCarId.suppCompanyCus.unitName}}</div>
          </template>

          <template v-else-if="col.field == 'operNote'">
            <span v-html="row.operNote.replace(/\(/g, '<br />').replace(/\)/g, '；<br />').replace(/&nbsp;,/g, '<br />')"></span>
          </template>

          <template v-else>{{ getColVal(row, col.field) }}</template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination 
      :total="dgPay.total" 
      :page.sync="dgPay.ps.page" 
      :limit.sync="dgPay.ps.rows" 
      @pagination="getDgList(2)"
    />

    <CollPayHedgedRecord
      v-if="collPayHedgedRecordMd.state"
      :myData="collPayHedgedRecordMd"
      @myClick="setCollPayHedgedRecordMd"
      @reloadDg="getDgList(0)"
    />

  </div>
</template>

<script>
import DataGridBase from "@/views/mixins/DataGridBase";
import DataGridResize from "@/views/mixins/DataGridResize";  
import Pagination from '@/components/Pagination';
import { exportExcel } from "@/utils/exportFile";

import CollPayHedgedRecord from './coll-pay-hedged-record';

import * as commService from "@/api/services/common.service";
import * as orderSer from "@/api/services/order.service";
import * as cusSer from "@/api/services/cus.service";

export default {
  name: "CollPayList",
  mixins: [DataGridResize, DataGridBase],
  components: { Pagination, CollPayHedgedRecord },
  data() {
    // 业务收款
    let colsColl = [
      { label: "车牌号", field: "plateNum", width: 100 },
      { label: "行程详情", field: "routeDetail", width: 'auto' },
      { label: "收款价格", field: "price", width: 80 },
      { label: "已收金额", field: "alGathPrice", width: 80 },
      { label: "应收金额", field: "receivableMoney", width: 80 },
      { label: "本次对冲金额", field: "currHedgedMoney", width: 100 },
      { label: "对冲后结差", field: "hedgedDiffMoney", width: 100 },
      { label: "业务员", field: "serviceMan", width: 150 },
      { label: "用车单位", field: "customId", width: 150 },
      { label: "备 注", field: "operNote", width: 250 },
    ];

    // 业务付款
    let colsPay = [
      { label: "车牌号", field: "plateNum", width: 100 },
      { label: "行程详情", field: "routeDetail", width: 'auto' },
      { label: "付款价格", field: "disPrice", width: 80 },
      { label: "已付金额", field: "alPayPrice", width: 80 },
      { label: "应付金额", field: "payableMoney", width: 80 },
      { label: "本次对冲金额", field: "currHedgedMoney", width: 100 },
      { label: "对冲后结差", field: "hedgedDiffMoney", width: 100 },
      { label: "业务员", field: "serviceMan", width: 150 },
      { label: "供车单位", field: "suppCompanyCus", width: 150 },
      { label: "备 注", field: "operNote", width: 250 },
    ];

    return {
      // 查询表单
      dgPs: { 
        // 用车开始时间 eg:yyyy-MM-dd
        startTime: "", 
        // 用车结束时间 eg:yyyy-MM-dd
        endTime: "", 
        // 业务员 eg:xxx
        serviceMan: "",
        // 行程详情
        routeDetail: "", 
        // 操作编号
        operMark: "",

        // 查询时间类型（固定传值）
        timeType: 1,
        // 支付状态（固定传值）
        payStatus: 'UNPAID,DEPOSIT_PAID',

        // 单位查询 对应：业务收款-用车方客户uname eg:xxxxx || 业务付款：供车方客户id eg:1
        companyId: '',
        // 单位联系人查询 对应：业务收款-用车方负责人uname eg:xxx || 业务付款：供车方负责人 eg:U1597129467768
        companyLinkman: '',
      },

      // 财务备注
      operNote: '',

      // 收款
      dgColl: {
        dgName: 'dgColl',
        tbName: "collPayOfCollectionListTb",
        total: 0,
        list: [],
        srcCols: colsColl,
        columns: [],
        selRows: [],
        ps: {
          page: 1, rows: 20,
        },
        // 选中总应收金额
        seledTotalCollMoney: 0,
      },

      // 付款列表
      dgPay: {
        dgName: 'dgPay',
        tbName: "collPayOfPaymentListTb",
        total: 0,
        list: [],
        srcCols: colsPay,
        columns: [],
        selRows: [],
        ps: {
          page: 1, rows: 20,
          // 是否自营（固定传值）
          useSelf: 0,
        },
        // 选中总应付金额 
        seledTotalPayMoney: 0,

      },
      // 选中总可对冲金额
      seledTotalHedgedMoney: 0,
      // 选中总对冲结差金额
      seledTotalHedgedDiffMoney: 0,

      // 订单状态
      payStatusArr: [
        { id: "UNPAID", name: "未付款" },
        { id: "DEPOSIT_PAID", name: "已付定金" },
        { id: "FULL_PAID", name: "全款已付" },
        { id: "APPLY_SUCCESS", name: "申请成功" },
      ],
      // 订单业务类型
      serviceTypeList: [
        { id: "COUNTY_SER", name: "县际业务" },
        { id: "CITY_SER", name: "市际业务" },
        { id: "PROVINCE_SER", name: "省际业务" },
      ],

      // 业务员-选择列表
      serviceManList: [],
      // 单位-选择列表 
      clientList: [], 
      // 联系人-选择列表
      dutyManList: [], 
      
      // 收付款对冲记录-弹框
      collPayHedgedRecordMd: {state: false},

    };
  },
  created() {
    const that = this;

    that.initTbSetData(that.dgColl.dgName);
    that.initTbSetData(that.dgPay.dgName);

    that.getCompanyAllSalesman();
    that.getDgList();
  },
  methods: {
    // 获取-单位所有业务员
    getCompanyAllSalesman() {
      cusSer.getCompanyAllSalesman({ staffState: "NORMAL,TRY" }).then((res) => {
        this.serviceManList = res.data;
      });
    },
    /**
     * 获取-单位客户-选择列表（用于下拉框）
     * @param find 客户手机号/用户名/姓名
     */
    queryCusPageList(find) {
      commService.queryComboCusPageList({find: find}).then((res) => {
        this.clientList = res?.data || [];
      });
    },
    // 选择客户-获取联系人
    selectCus(it) {
      const that = this, ps = that.dgPs;

      ps.companyId = it.id;
      ps.companyLinkman = "";
      orderSer.geDutysByCuList({ cusUname: it.baseUserId.uname }).then((res) => {
        that.dutyManList = res.data;
        // 默认选中第一个
        if(that.dutyManList.length > 0) ps.companyLinkman = that.dutyManList[0].uname;
      });
    },

    // 获取-表格列表
    async getDgList(type = 0) {
      const that = this, U = that.U, ps = U.scopy(that.dgPs);
      
      // 查询应收数据列表
      if(type == 0 || type == 1){
        let dg = that.dgColl;
        // 清空选中数据
        dg.selRows = [];

        let collPs = {...ps, ...dg.ps};
        // 业务收款-用车方客户uname eg:xxxxx
        collPs.customId = collPs.companyId;
        delete collPs.companyId;
        // 业务收款-用车方负责人uname eg:xxx
        collPs.dutyService = collPs.companyLinkman;
        delete collPs.companyLinkman;

        let collRes = await orderSer.getMainCarOrderForCollection(collPs);
        if (collRes.code == 1) {
          let list = collRes.data;
          list.forEach(it => {
            it.dgName = dg.dgName;

            // 应收金额
            it.receivableMoney = (parseFloat(it.price) - parseFloat(it.alGathPrice)).toFixed(2);
            // 本次对冲金额
            it.currHedgedMoney = '';
            // 对冲后结差
            it.hedgedDiffMoney = '';
            
            if (it.carOrders) {
              // 所有驾驶员信息
              let allDriverInfo = [];
              // 所有的行程详情
              let allRouteDetail = [];
              // 所有客户备注
              let allCusNote = [];
              // 所有驾驶员备注
              let allDriverNote = [];
              // 所有业务员备注
              let allServiceNote = [];
              it.carOrders.forEach(co => {
                // 获取-所有子单-驾驶员信息
                if(co.disCarId){
                  let driverInfo = {plateNum: co.disCarId.plateNum};
                  if(co.disCarId.mainDriver){// 主驾
                    driverInfo.uname = co.disCarId.mainDriver.uname;
                    driverInfo.realName = co.disCarId.mainDriver.realName;
                    driverInfo.phone = co.disCarId.mainDriver.phone;
                  }else if(co.outDriverInfo){// 外调车驾驶员
                    driverInfo.uname = '';
                    driverInfo.realName = co.outDriverInfo.split(',')[1];
                    driverInfo.phone = co.outDriverInfo.split(',')[0];
                  }
                  allDriverInfo.push(driverInfo);
                }

                // 累加行程详情
                allRouteDetail.push(co.routeDetail.replace(/@/g, ''));
                // 累加客户备注
                allCusNote.push(co.cusNote);
                // 累加驾驶员备注
                allDriverNote.push(co.driverNote);
                // 累加业务员备注
                allServiceNote.push(co.serviceNote); 

              });
              // 设置-所有-驾驶员信息
              it.driverInfo = allDriverInfo;
              // 设置-所有-行程详情
              it.routeDetail = allRouteDetail;
              // 设置-所有-客户备注
              let notesA = [];
              allCusNote.forEach(cn => {
                let ai = notesA.findIndex(ait => ait == cn);
                if(cn && ai == -1) notesA.push(cn);
              });
              it.cusNote = notesA;
              // 设置-所有-驾驶员备注
              let notesB = [];
              allDriverNote.forEach(dn => {
                let bi = notesB.findIndex(bit => bit == dn);
                if(dn && bi == -1) notesB.push(dn);
              });
              it.driverNote = notesB;
              // 设置-所有-业务员备注
              let notesC = [];
              allServiceNote.forEach(sn => {
                let ci = notesC.findIndex(cit => cit == sn);
                if(sn && ci == -1) notesC.push(sn);
              });
              it.serviceNote = notesC;
            }
          
          });
          console.log('应收列表', list);

          dg.list = list;
          dg.total = collRes.count;
        }
      }


      // 查询应付数据列表
      if(type == 0 || type === 2){
        let dg = that.dgPay;
        // 清空选中数据
        that.dgPay.selRows = [];

        let payPs = {...ps, ...dg.ps};
        // 业务付款：供车方客户id eg:1
        payPs.suppCusId = payPs.companyId;
        delete payPs.companyId;
        // 业务付款：供车方负责人 eg:U1597129467768
        payPs.suppMan = payPs.companyLinkman;
        delete payPs.companyLinkman;

        let payRes = await orderSer.getCarOrderListForPayList(payPs);
        if (payRes.code == 1) {
          let list = payRes.data;
          list.forEach(it => {
            it.dgName = dg.dgName;

            // 应付金额
            it.payableMoney = (parseFloat(it.disPrice) - parseFloat(it.alPayPrice)).toFixed(2);
            it.currHedgedMoney = '';
            it.hedgedDiffMoney = '';
          });
          console.log('应付列表', list);

          dg.list = list;
          dg.total = payRes.count;
        }
      }
    },
    // 处理收款/付款订单选中列表数据
    handlerDgList(){
      const that = this, dgColl = that.dgColl, dgPay = that.dgPay;

      // 应收总金额 = 每单收款价格 - 每单已收金额
      dgColl.seledTotalCollMoney = dgColl.selRows.reduce((sum, it) => {return sum+(it.price - it.alGathPrice);}, 0);
      // console.log('应收总金额：', dgColl.seledTotalCollMoney);

      // 应付总金额 = 每单付款价格 - 每单已付金额
      dgPay.seledTotalPayMoney = dgPay.selRows.reduce((sum, it) => {return sum+(it.disPrice - it.alPayPrice);}, 0);
      // console.log('应付总金额：', dgPay.seledTotalPayMoney);

      // 选中总应收金额 > 选中总应付金额，则可对冲金额=选中总应付金额，反之可对冲金额=选中总应收金额
      if (Number(dgColl.seledTotalCollMoney) > Number(dgPay.seledTotalPayMoney)) {
        that.seledTotalHedgedMoney = Number(dgPay.seledTotalPayMoney);
      } else {
        that.seledTotalHedgedMoney = Number(dgColl.seledTotalCollMoney);
      }
      // 选中总对冲结差金额
      that.seledTotalHedgedDiffMoney = Math.abs(Number(dgColl.seledTotalCollMoney) - Number(dgPay.seledTotalPayMoney));


      // 处理应收列表
      let tempSeledTotalPayMoney = dgPay.seledTotalPayMoney;
      dgColl.list.forEach(it => {
        let is = dgColl.selRows.find(a => a.id == it.id);
        if(!is){
          // 本次对冲金额、对冲后结差 清空
          it.currHedgedMoney = '';
          it.hedgedDiffMoney = '';
        }else{
          // 每单应收金额 = 每单收款价格 - 每单已收金额
          it.receivableMoney = (it.price - it.alGathPrice).toFixed(2);

          // 【应收 小于 应付】 应收对冲完
          if(dgColl.seledTotalCollMoney < dgPay.seledTotalPayMoney){
            // 本次对冲金额 = 应收金额，即平完
            it.currHedgedMoney = it.receivableMoney;
            // 对冲后结差 = 0
            it.hedgedDiffMoney = 0;
          }else{// 【应收 大于 应付】 应收每个订单用应付总金额去循环对冲（依次减）
            // 总应付金额 < 本次应收金额
            if(tempSeledTotalPayMoney < it.receivableMoney){
              // 本次对冲金额 = 总应付金额，即未平完（本次应收金额有剩余）
              it.currHedgedMoney = tempSeledTotalPayMoney;
              // 对冲后结差 = 本次应收金额 - 总应付金额（大的-小的）
              it.hedgedDiffMoney = it.receivableMoney - tempSeledTotalPayMoney;

              // 剩余总应付金额为0
              tempSeledTotalPayMoney = 0;
            }else{
              // 本次对冲金额 = 应收金额，即本次已对冲完
              it.currHedgedMoney = it.receivableMoney;
              // 对冲后结差 = 0
              it.hedgedDiffMoney = 0; 

              // 剩余总应付金额
              tempSeledTotalPayMoney -= it.receivableMoney;
              // 剩余总应付金额最小为0
              if(tempSeledTotalPayMoney <= 0) tempSeledTotalPayMoney = 0;
            }
          }
        }
      });


      // 应付列表
      let tempSeledTotalCollMoney = dgColl.seledTotalCollMoney;
      dgPay.list.forEach(it => {
        let is = dgPay.selRows.find(a => a.id == it.id);
        if(!is){
          // 本次对冲金额、对冲后结差 清空
          it.currHedgedMoney = '';
          it.hedgedDiffMoney = '';
        }else{
          // 每单应付金额 = 每单派车金额 - 每单已付金额
          it.payableMoney = (it.disPrice - it.alPayPrice).toFixed(2);

          // 【应付 小于 应收】 应付对冲完
          if(dgPay.seledTotalPayMoney <= dgColl.seledTotalCollMoney){
            // 对冲金额 = 应付金额，即对冲完
            it.currHedgedMoney = it.payableMoney;
            // 对冲后结差 = 0
            it.hedgedDiffMoney = 0;
          }else{// 【应付 大于 应收】 应付每个订单用应收总金额去循环对冲（依次减）
            // 总应收金额 < 本次应付金额
            if(tempSeledTotalCollMoney < it.payableMoney){
              // 对冲金额 = 总应收金额，即未对冲完（本单应付金额有剩余）
              it.currHedgedMoney = tempSeledTotalCollMoney;
              // 对冲后结差 = 本单应付金额 - 总应收金额
              it.hedgedDiffMoney = it.payableMoney - tempSeledTotalCollMoney;

              // 剩余总应收金额为0
              tempSeledTotalCollMoney = 0;
            }else{
              // 对冲金额 = 应付金额，即本次已对冲完
              it.currHedgedMoney = it.payableMoney;
              // 对冲后结差 = 0
              it.hedgedDiffMoney = 0;

              // 剩余总应收金额
              tempSeledTotalCollMoney -= it.payableMoney;
              // 剩余总应收金额最小为0
              if(tempSeledTotalCollMoney <= 0) tempSeledTotalCollMoney = 0;
            }
          }
        }
      });
      
    },

    /**
     * 选中行/收款
     * @param selection 选中的所有行
     * @param row       当前被点击的行
     */
    selRowColl(selection, row) {
      const that = this, dg = that.dgColl, dgPay = that.dgPay;

      // 设置-选中的所有行数据
      dg.selRows = selection;

      that.handlerDgList();
    },

    /**
     * 选中所有行/收款
     * @param selection 选中的所有行
     */
    selRowCollAll(selection) {
      this.selRowColl(selection, null);
    },

    /**
     * 选中行/付款
     * @param selection 选中的所有行
     * @param row       当前被点击的行
     */
    selRowPay(selection, row) {
      const that = this, dg = that.dgPay, dgColl = that.dgColl;
      
      // 设置-选中的所有行数据
      dg.selRows = selection;

      that.handlerDgList();
    },
    /**
     * 选中所有行/付款
     * @param selection 选中的所有行
     * @param row       当前被点击的行
     */
    selRowPayAll(selection) {
      this.selRowPay(selection, null);
    },
    // 确认对冲
    confirmHedge(){
      const that = this, U = that.U, FV = that.FV, dgColl = that.dgColl, dgPay = that.dgPay;

      // 收款订单和付款订单均需至少选中一条
      if(dgColl.selRows.length == 0 || dgPay.selRows.length == 0){
        return U.qerror('[收款订单]和[付款订单]均需至少选中一条');
      }

      // 收款订单中只能有【未结清】的订单
      let isObj = dgColl.selRows.find(it => (it.payStatus != 'UNPAID' && it.payStatus != 'DEPOSIT_PAID'));
      if(isObj) return U.qerror(`[收款订单]中第${isObj.index+1}行订单不是【未结清】，请重新选择`);

      // 付款订单中只能有【未结清】的订单
      isObj = dgPay.selRows.find(it => (it.payStatus != 'UNPAID' && it.payStatus != 'DEPOSIT_PAID'));
      if(isObj) return U.qerror(`[付款订单]中第${isObj.index+1}行订单不是【未结清】，请重新选择`);

      U.qconfim("确认对冲吗？").then(r => {
        if(r){
          // 准备提交参数对象数据
          let gathInfoArr = [];
          dgColl.selRows.forEach(it => {
            gathInfoArr.push({ orderId: it.id, gathMoney: it.currHedgedMoney });
          });

          let payInfoArr = [];
          dgPay.selRows.forEach(it => {
            payInfoArr.push({ orderId: it.id, payMoney: it.currHedgedMoney });
          });

          let remark = '';
          if(!that.operNote || FV.trim(that.operNote).length == 0){
            return U.qerror('财务备注不能为空');
          }else{
            remark = FV.trim(that.operNote);
          }

          let ps = {gathInfo: gathInfoArr, payInfo: payInfoArr, remark: remark};
          orderSer.serviceOffSet(ps).then(res => {
            if(res.code != 1){
              U.qerror(res.msg);
            }else{
              U.qsuccess(res.msg);

              that.getDgList();
            }
          });
        }
      });
    },

    // 撤销-对冲
    cancelHedge() {
      const that = this, U = that.U, collRows = that.dgColl.selRows, payRows = that.dgPay.selRows;
      
      if (collRows.length === 0 && payRows.length === 0) {
        U.qerror("请选择一条数据");
      } else if (collRows.length >= 1 && payRows.length >= 1) {
        U.qerror("请选择一条数据");
      } else {
        if (collRows.length > 1) {
          U.qerror("请选择一条收款数据");
        } else if (payRows.length > 1) {
          U.qerror("请选择一条付款数据");
        } else {
          if (collRows.length === 1) {
            var markNum = collRows[0].voucherNum;
          } else if (payRows.length === 1) {
            var markNum = payRows[0].voucherNum;
          }
        }

        U.qconfim("确认撤销业务对冲吗？").then(r => {
          if(r){
            orderSer.cancelOffSetList({ cancelOffSetNum: markNum }).then((res) => {
              if (!res || res.code != 1) {
                U.qerror(res.msg);
              } else {
                U.qsuccess(res.msg);
                that.getDgList();
              }
            });
          }
        });
      }
    },

    // 显示/隐藏-收付款对冲记录-弹框
    setCollPayHedgedRecordMd(e){
      this.collPayHedgedRecordMd = e;
    },

    // 导出excel
    async onExportExcel(type = 0){
      const that = this, U = that.U, ps = U.scopy(that.dgPs);

      if(!ps.companyId) return U.qerror('请选择一个单位查询');
      
      // 查询应收数据列表
      let collExportList = [];
      if(type == 0 || type == 1){
        let dg = that.dgColl;

        // 导出数据为总条数
        dg.rows = dg.total;
        await that.getDgList(1);
        
        // 处理数据
        dg.list.forEach(it => {
          let o = {};
          // 车牌号
          o.plateNums = it.driverInfo.map(a => a.plateNum).join('，');
          // 行程详情
          o.routeDetail = it.routeDetail.join('；');
          // 收款价格
          o.price = it.price;
          // 已收金额
          o.alGathPrice = it.alGathPrice;
          // 应收金额
          o.receivableMoney = it.receivableMoney;
          // 本次对冲金额
          o.currHedgedMoney = it.currHedgedMoney;
          // 对冲后结差
          o.hedgedDiffMoney = it.hedgedDiffMoney;
          // 业务员
          o.serviceMan = it.carOrderBase.serviceMan?.split('-')[1]+'-'+it.carOrderBase.serviceMan?.split('-')[2];
          // 用车单位
          o.customId = it.carOrderBase.customId.unitName;
          // 备注
          o.operNote = it.operNote.replace('&nbsp;', '');

          // 加入列表
          collExportList.push(o);
        });
        console.log('业务收款导出数据-处理前', collExportList);
      }


      // 查询应付数据列表
      let payExportList = [];
      if(type == 0 || type === 2){
        let dg = that.dgPay;
        // 清空选中数据
        that.dgPay.selRows = [];
        
        // 导出数据为总条数
        dg.rows = dg.total;
        await that.getDgList(2);
        
        // 处理数据
        dg.list.forEach(it => {
          let o = {};
          // 车牌号
          o.plateNum = it.disCarId?.plateNum;
          // 行程详情
          o.routeDetail = it.routeDetail;
          // 付款价格
          o.disPrice = it.disPrice;
          // 已付金额
          o.alPayPrice = it.alPayPrice;
          // 应付金额
          o.payableMoney = it.payableMoney;
          // 本次对冲金额
          o.currHedgedMoney = it.currHedgedMoney;
          // 对冲后结差
          o.hedgedDiffMoney = it.hedgedDiffMoney;
          // 业务员
          o.serviceMan = it.carOrderBase.serviceMan?.split('-')[1]+'-'+it.carOrderBase.serviceMan?.split('-')[2];
          // 供车单位
          o.suppCompanyCus = it.disCarId.suppCompanyCus.unitName;
          // 备注
          o.operNote = it.operNote.replace('&nbsp;', '');

          // 加入列表
          payExportList.push(o);
        });
        console.log('业务付款导出数据-处理前', payExportList);
      }

      let collPayExportListArr = that.handlerExcelDgList(collExportList, payExportList);

      // 导出【业务收款订单Excel】
      if(collPayExportListArr[0].length <= 0){
        U.qerror('【业务收款订单无数据，不能导出】');
      }else{
        exportExcel({
          filename: "业务收款订单列表",
          data: collPayExportListArr[0],
          enumData: {
            plateNums: "车牌号",
            routeDetail: "行程详情",
            price: "收款价格",
            alGathPrice: "已收金额",
            receivableMoney: "应收金额",
            currHedgedMoney: "本次对冲金额",
            hedgedDiffMoney: "对冲后结差",
            serviceMan: "业务员",
            customId: "用车单位",
            operNote: "备 注",
          },
        });
      }

      // 导出【业务付款订单Excel】
      if(collPayExportListArr[1].length <= 0){
        U.qerror('【业务付款订单无数据，不能导出】');
      }else{
        exportExcel({
          filename: "业务付款订单列表",
          data: collPayExportListArr[1],
          enumData: {
            plateNum: "车牌号",
            routeDetail: "行程详情",
            disPrice: "付款价格",
            alPayPrice: "已付金额",
            payableMoney: "应付金额",
            currHedgedMoney: "本次对冲金额",
            hedgedDiffMoney: "对冲后结差",
            serviceMan: "业务员",
            suppCompanyCus: "供车单位",
            operNote: "备 注",
          },
        });
      }

    },

    // 处理收款/付款导出excel列表数据
    handlerExcelDgList(collList = [], payList = []){
      const that = this;

      // 应收总金额 = 每单收款价格 - 每单已收金额
      let seledTotalCollMoney = collList.reduce((sum, it) => {return sum+(it.price - it.alGathPrice);}, 0);
      console.log('应收总金额：', seledTotalCollMoney);

      // 应付总金额 = 每单付款价格 - 每单已付金额
      let seledTotalPayMoney = payList.reduce((sum, it) => {return sum+(it.disPrice - it.alPayPrice);}, 0);
      console.log('应付总金额：', seledTotalPayMoney);

      // 处理应收列表
      let tempSeledTotalPayMoney = seledTotalPayMoney;
      collList.forEach(it => {
        // 每单应收金额 = 每单收款价格 - 每单已收金额
        it.receivableMoney = (it.price - it.alGathPrice).toFixed(2);

        // 【应收 小于 应付】 应收对冲完
        if(seledTotalCollMoney < seledTotalPayMoney){
          // 本次对冲金额 = 应收金额，即平完
          it.currHedgedMoney = it.receivableMoney;
          // 对冲后结差 = 0
          it.hedgedDiffMoney = 0;
        }else{// 【应收 大于 应付】 应收每个订单用应付总金额去循环对冲（依次减）
          // 总应付金额 < 本次应收金额
          if(tempSeledTotalPayMoney < it.receivableMoney){
            // 本次对冲金额 = 总应付金额，即未平完（本次应收金额有剩余）
            it.currHedgedMoney = tempSeledTotalPayMoney;
            // 对冲后结差 = 本次应收金额 - 总应付金额（大的-小的）
            it.hedgedDiffMoney = it.receivableMoney - tempSeledTotalPayMoney;

            // 剩余总应付金额为0
            tempSeledTotalPayMoney = 0;
          }else{
            // 本次对冲金额 = 应收金额，即本次已对冲完
            it.currHedgedMoney = it.receivableMoney;
            // 对冲后结差 = 0
            it.hedgedDiffMoney = 0; 

            // 剩余总应付金额
            tempSeledTotalPayMoney -= it.receivableMoney;
            // 剩余总应付金额最小为0
            if(tempSeledTotalPayMoney <= 0) tempSeledTotalPayMoney = 0;
          }
        }
      });


      // 应付列表
      let tempSeledTotalCollMoney = seledTotalCollMoney;
      payList.forEach(it => {
        // 每单应付金额 = 每单派车金额 - 每单已付金额
        it.payableMoney = (it.disPrice - it.alPayPrice).toFixed(2);

        // 【应付 小于 应收】 应付对冲完
        if(seledTotalPayMoney <= seledTotalCollMoney){
          // 对冲金额 = 应付金额，即对冲完
          it.currHedgedMoney = it.payableMoney;
          // 对冲后结差 = 0
          it.hedgedDiffMoney = 0;
        }else{// 【应付 大于 应收】 应付每个订单用应收总金额去循环对冲（依次减）
          // 总应收金额 < 本次应付金额
          if(tempSeledTotalCollMoney < it.payableMoney){
            // 对冲金额 = 总应收金额，即未对冲完（本单应付金额有剩余）
            it.currHedgedMoney = tempSeledTotalCollMoney;
            // 对冲后结差 = 本单应付金额 - 总应收金额
            it.hedgedDiffMoney = it.payableMoney - tempSeledTotalCollMoney;

            // 剩余总应收金额为0
            tempSeledTotalCollMoney = 0;
          }else{
            // 对冲金额 = 应付金额，即本次已对冲完
            it.currHedgedMoney = it.payableMoney;
            // 对冲后结差 = 0
            it.hedgedDiffMoney = 0;

            // 剩余总应收金额
            tempSeledTotalCollMoney -= it.payableMoney;
            // 剩余总应收金额最小为0
            if(tempSeledTotalCollMoney <= 0) tempSeledTotalCollMoney = 0;
          }
        }
      });
      
      return [collList, payList];
    },


  },
};
</script>

<style scoped lang="less">
.collpay-list {
  .dc-list {
    display: flex;
    align-items: center;
  }
  .collpay-head {
    font-size: 15px;
    font-weight: 600;
    margin: 0px 0px 10px 0px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  }
  .collpay-title {
    width: auto;
    display: flex;
    border-left: 1px solid #ff6600;
    align-items: center;
    color: #333;
    padding: 5px 10px 5px 5px;
    border-radius: 4px;
    .t-title{
      font-size: 14px;
    }
  }
  .collpay-title > div {
    font-size: 12px;
  }
  .collpay-title > div:first-child {
    width: auto;
  }
  .collpay-totle {
    display: flex;
    width: 100%;
    align-items: center;
    margin: 10px 0px;
    border-radius: 4px;
    padding: 5px;
    background: #ccc;
    > div {
      font-size: 12px;
      font-weight: 600;
      &:last-child{
        margin-left: 20px;
      }
    }
    .t-title{
      font-size: 17px;
    }
  }
  .collpay-type {
    display: flex;
    font-size: 12px;
    align-items: center;
    margin-right: 30px;
  }
  .collpay-type > div:first-child {
    margin-right: 10px;
  }
}
</style>
